import React, { useEffect, useState } from 'react';

const UserManager = ({ onLogout }) => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [resetUser, setResetUser] = useState(null);
  const [newPassword, setNewPassword] = useState('');
  const [msg, setMsg] = useState('');
  const token = localStorage.getItem('token');

  const fetchUsers = async () => {
    setLoading(true);
    const res = await fetch('/api/users', {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    const data = await res.json();
    setUsers(data.users || []);
    setLoading(false);
  };

  useEffect(() => {
    fetchUsers();
    // eslint-disable-next-line
  }, []);

  const handleReset = async () => {
    if (!newPassword || newPassword.length < 6) {
      setMsg('新密码至少6位');
      return;
    }
    const res = await fetch(`/api/users/${resetUser.id}/reset-password`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({ newPassword })
    });
    const data = await res.json();
    setMsg(data.message);
    if (res.ok) {
      setTimeout(() => {
        setResetUser(null);
        setNewPassword('');
        setMsg('');
      }, 1200);
    }
  };

  return (
    <div style={{ maxWidth: 800, margin: '0 auto', background: '#fff', borderRadius: 16, boxShadow: '0 4px 24px #e3e8f0', padding: 32, position: 'relative' }}>
      {/* 右上角登出按钮 */}
      <button onClick={onLogout} style={{ position: 'absolute', right: 32, top: 32, background: 'linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%)', color: '#fff', border: 0, borderRadius: 18, padding: '7px 28px', fontWeight: 600, letterSpacing: 1, boxShadow: '0 2px 8px rgba(252, 92, 125, 0.12)', cursor: 'pointer' }}>登出</button>
      <h2 style={{ marginBottom: 24, color: '#6a82fb', letterSpacing: 2 }}>用户管理</h2>
      <div style={{ overflowX: 'auto' }}>
        {loading ? '加载中...' : (
          <table style={{ width: '100%', borderCollapse: 'separate', borderSpacing: 0, fontSize: 15 }}>
            <thead>
              <tr style={{ background: '#f3f6fd', color: '#6a82fb' }}>
                <th style={{ textAlign: 'left', padding: '10px 8px' }}>用户名</th>
                <th>邮箱</th>
                <th>注册时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {users.map(user => (
                <tr key={user.id} style={{ background: '#fff' }}>
                  <td style={{ padding: '8px 8px' }}>{user.username}</td>
                  <td style={{ textAlign: 'center' }}>{user.email}</td>
                  <td style={{ textAlign: 'center', color: '#888' }}>{user.created_at?.slice(0, 19).replace('T', ' ')}</td>
                  <td style={{ textAlign: 'center' }}>
                    <button onClick={() => { setResetUser(user); setMsg(''); setNewPassword(''); }} style={{ background: '#e6edfa', color: '#6a82fb', border: 0, borderRadius: 6, padding: '5px 14px', fontWeight: 500 }}>重置密码</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
      {/* 重置密码弹窗 */}
      {resetUser && (
        <div style={{ position: 'fixed', left: 0, top: 0, width: '100vw', height: '100vh', background: 'rgba(0,0,0,0.18)', zIndex: 99, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ background: '#fff', borderRadius: 12, padding: 36, minWidth: 340, boxShadow: '0 2px 16px #aaa', position: 'relative' }}>
            <h3 style={{ color: '#6a82fb', marginBottom: 18 }}>重置密码 - {resetUser.username}</h3>
            <input
              type="password"
              placeholder="新密码（至少6位）"
              value={newPassword}
              onChange={e => setNewPassword(e.target.value)}
              style={{ width: '100%', margin: '16px 0', padding: 10, borderRadius: 8, border: '1px solid #e3e8f0', fontSize: 16 }}
            />
            <div style={{ color: msg.startsWith('密码重置') ? 'green' : 'red', minHeight: 22, fontSize: 15 }}>{msg}</div>
            <div style={{ marginTop: 18, textAlign: 'right' }}>
              <button onClick={() => setResetUser(null)} style={{ marginRight: 16, background: '#eee', border: 0, borderRadius: 6, padding: '8px 18px', fontWeight: 500 }}>取消</button>
              <button onClick={handleReset} style={{ background: '#6a82fb', color: '#fff', border: 0, borderRadius: 6, padding: '8px 24px', fontWeight: 600 }}>确认重置</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default UserManager; 